const CommentModel = require('../model/comment')

exports.add = async (req, res, next) => {
    try {
        let result = await CommentModel.add(req.fields)
        // console.log(result);
        res.send({ status: 'success', msg: '留言添加成功', data: { id: result[0].insertId } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '留言添加失败' })
    }
}

exports.delete = async (req, res, next) => {
    try {
        // console.log(req.params);
        let result = await CommentModel.delete(req.params.id)
        res.send({ status: 'success', msg: '留言删除成功', data: { affectedRows: result[0].affectedRows } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '留言删除失败' })
    }
}

exports.findByFid = async (req, res, next) => {
    try {
        // console.log(req.params.fid,req.query.pageIndex);
        let result = await CommentModel.findByFid(req.params.fid, req.query.pageIndex)
        let total = await CommentModel.findAll(req.params.fid)
        let totalPage = Math.ceil(total[0].total / 10)
        // console.log(totalPage);
        res.send({ status: 'success', msg: '留言查找成功', data: { list: result, totalPage } })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '留言查找失败' })
    }
}

exports.findAll = async (req, res, next) => {
    try {
        let result = await CommentModel.findAll(req.params.fid)
        res.send({ status: 'success', msg: '留言查找成功', data: result })
    } catch (error) {
        console.log(error);
        next({ status: 'fail', msg: '留言查找失败' })
    }
}